package com.beeasy.hzbpm.ctrl;

import com.beeasy.hzbpm.filter.Auth;
import com.beeasy.hzbpm.service.msgService;
import com.github.llyb120.nami.core.Config;
import com.github.llyb120.nami.core.MultipartFile;
import com.github.llyb120.nami.core.RestException;
import com.github.llyb120.nami.ctrl.Ctrl;
import com.github.llyb120.json.Arr;
import com.github.llyb120.json.Json;
import com.github.llyb120.json.Obj;

import java.util.Date;
import java.util.Map;

import static com.beeasy.hzbpm.bean.FileStorage.storage;
import static com.github.llyb120.nami.core.Config.config;
import static com.github.llyb120.json.Json.o;
import static com.beeasy.hzbpm.bean.MongoService.db;
import static com.github.llyb120.json.Json.*;
/**
 * @Author: Stunievi
 * @Date: 2019/12/27 16:04
 */
public class message extends Ctrl {
    /**
     * 发送消息
     * */
    public Object sendMsg(){
        String content = $post.s("content");
        Arr toUid = Json.parse($post.s("to_uid"));
        if(toUid.size() == 0){
            throw new RestException("用户不能为空");
        }
        if(content == null || content.equals("")){
            throw new RestException("不能发送空消息");
        }
        Arr bindData = null;
        if($post.s("bind_data").length() != 0){
            bindData = Json.parse($post.s("bind_data"));
        }
        // 消息主体
        for (Object v : toUid){
            String id = v.toString();
            Obj info = o(
                    "add_time", new Date(),
                    "bind_data", bindData,
                    "content",content.replaceAll("[\"]", "\\\\$0").replaceAll("[']", "\\\\$0"),
                    "state","UNREAD",
                    "type","MESSAGE",
                    "user_id",id,
                    "from_uid", Auth.getUid()
            );
//            System.err.println(info);
            new msgService().sendMsg(info);
        }



        return null;
    }
    /**
     * 上传文件
     *
     * */
    public Object uploads(MultipartFile file){

        try{
//            $.files
//            System.out.println(file.length());
            return o("id",storage.upload(file),"name",file.fileName);
//            return new msgService().uploadFiles(file, config.var.s("uplaod"));
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }
    /**
     * 删除附件
     * */
    public Object removeFile(){
//        String id = $get.s("id");
//        Arr data = db.getCollection("saveFiles").find(o(
//                "id",id
//        ).toBson()).into(a());
//        data;
        return null;
    }
    /**
     * 下载附件
     * */
    public MultipartFile download(){
        String id = $get.s("id");
        String name = $get.s("name");
        MultipartFile file = storage.download(id);
        file.fileName = name;
        return file;
    }
    /**
     * 消息列表
     * */
    public Object inbox(){
        int page = $get.i("page");
        if(page != 1){
            page = (page - 1)  * 10;
        }else{
            page = 0;
        }
        Obj codition = o(
                "user_id",Auth.getUid()
        );
        Arr data = db.getCollection("system_notice").find(codition.toBson()).limit(10).skip(page).sort(o(
                "add_time",-1
        ).toBson()).into(new Arr());
        Arr count = db.getCollection("system_notice").aggregate(
                a(
                        o("$match",codition),
                        o("$project",o("id","$id")),
                        o("$count","count")
                ).toBson()
        ).into(a());
//        System.err.println(count.get(0));
        Arr list = operation(data);
        if(count.size() == 0){
            return o("data",null,"totalRow",0);
        }
        return o("data",list,"totalRow",((Map)count.get(0)).get("count"));
    }
    /**
     * 消息列表 发件箱
     * */
    public Object inboxF(){
        int page = $get.i("page",1);
        if(page != 1){
            page = (page - 1)  * 10;
        }else{
            page = 0;
        }
        Obj codition = o(
                "from_uid",Auth.getUid()
        );
        Arr data = db.getCollection("system_notice").find(codition.toBson()).limit(10).skip(page).sort(o(
                "add_time",-1
        ).toBson()).into(new Arr());
        Arr count = db.getCollection("system_notice").aggregate(
                a(
                        o("$match",codition),
                        o("$project",o("id","$id")),
                        o("$count","count")
                ).toBson()
        ).into(a());
//        System.err.println(count.get(0));
        Arr list = operation(data);
        list.forEach( k->{
            Map mp = (Map)k;
            if(mp.get("user_id") != null) {
                Arr user = db.getCollection("user").find(o(
                        "id", mp.get("user_id")
                ).toBson()).into(a());
//                System.err.println(((Map) user.get(0)));
                mp.put("true_name", ((Map) user.get(0)).get("true_name"));
            }
//            if(mp.get("true_name") == null){
//                mp.put("true_name","系统");
//            }
        });
        if(count.size() == 0){
            return o("data",null,"totalRow",0);
        }
        return o("data",list,"totalRow",((Map)count.get(0)).get("count"));
    }
    /**
     * 消息修改为查看 READ
     * */
    public Object alread(){
        Arr list = (Arr) Json.parse($get.s("id"));
        db.getCollection("system_notice")

                .updateMany(
                        o("id", o("$in",list),"user_id",Auth.getUid()).toBson(),

                        o("$set",o("state","READ")).toBson()
                );
        return null;
    }
    /**
     *  收件箱 搜索
     *
     * */
    public Object search(){
        String name = $get.s("name");
        String typeValue = $get.s("typeValue");
        String stateValue = $get.s("stateValue");
        int page = $get.i("page",1);

        Obj where = o(
                "user_id",Auth.getUid()
        );

        Obj result = searchMsg(name,typeValue,stateValue,where,page);

        return result;
    }
    /**
     *  发件箱 搜索
     *
     * */
    public Object searchF(){
        String name = $get.s("name");
        String typeValue = $get.s("typeValue");
        String stateValue = $get.s("stateValue");

        Obj where = o(
            "from_uid",Auth.getUid()
        );
        int page = $get.i("page",1);


        Obj result = searchMsg(name,typeValue,stateValue,where,page);
        ((Arr)result.get("data")).forEach( k->{
            Map mp = (Map)k;
            if(mp.get("user_id") != null) {
                Arr user = db.getCollection("user").find(o(
                        "id", mp.get("user_id")
                ).toBson()).into(a());
//                System.err.println(((Map) user.get(0)));
                mp.put("true_name", ((Map) user.get(0)).get("true_name"));
            }
        });
        return result;
    }
    /**
     * 搜索公共方法
     * */
    private Obj searchMsg(String name,String typeValue,String stateValue,Obj where,int page){

        if(page != 1){
            page = (page - 1)  * 10;
        }else{
            page = 0;
        }
        Obj codition = o(
                "true_name",name
        );
        if(name != null && !name.equals("")){
            Arr data = db.getCollection("user").find(codition.toBson()).into(new Arr());

            if(data.size() != 0){
                Arr userList = a();
                for( Object i : data){
                    userList.add(((Map)i).get("id"));
                }
                where.put("user_id",o("$in",userList));
            }
        }
        if(typeValue != null && !typeValue.equals("")){
            where.put("type",typeValue);
        }
        if(stateValue != null && !stateValue.equals("")){
            where.put("state",stateValue);
        }
        Arr list = db.getCollection("system_notice").find(where.toBson()).sort(
                o("add_time",-1).toBson()
        ).limit(10).skip(page).into(new Arr());
//        System.err.println(where.toBson());
        Arr count = db.getCollection("system_notice").aggregate(
                a(
                        o("$match",where),
                        o("$count","count")

                ).toBson()
        ).into(a());
        if(count.size() == 0){
            return o("data",a(),"totalRow",0);
        }
        list = operation(list);
        return o("data",list,"totalRow",((Map)count.get(0)).get("count"));
    }
    /**
     *
     * */
    public Object del(){
        Arr list = (Arr) Json.parse($get.s("id"));
        db.getCollection("system_notice")
                .deleteMany(
                        o("id", o("$in",list),"user_id",Auth.getUid()).toBson()
                );
        return null;
    }
    /**
     * 返回消息类型
     *
     * */
    public Object returnType(){
        Arr type = db.getCollection("system_notice").aggregate(
                a(
                        o("$group",o("_id","$type")),
                        o("$project",o("type","$_id"))
                ).toBson()
        ).into(a());
        Arr state = db.getCollection("system_notice").aggregate(
                a(
                        o("$group",o("_id","$state")),
                        o("$project",o("state","$_id"))
                ).toBson()
        ).into(a());
        return o("type",type,"state",state);
    }
    /**
     * viewMsg 消息查看
     * */
    public Object viewMsg(){
        Obj codition = o(
                "id",$get.s("id")
        );
        Arr data = db.getCollection("system_notice").find(codition.toBson()).into(new Arr());
        if(data.size() == 0){
            throw new RestException("无此信息");
        }
        Arr list = operation(data);
        if(((Map)data.get(0)).get("from_uid") != null){

            Arr userInfo = db.getCollection("user").find(o(
                    "id",((Map)data.get(0)).get("from_uid")
            ).toBson()).into(new Arr());

            ((Map)list.get(0)).put("true_name",((Map)userInfo.get(0)).get("true_name"));
//        System.err.println(((Map)userInfo.get(0)).get("true_name"));
            return list.get(0);
        }

        ((Map)list.get(0)).put("true_name","系统");
//        System.err.println(((Map)userInfo.get(0)).get("true_name"));
        return list.get(0);

    }
    /**
     * 处理一下消息数据
     *
     * */
    private Arr operation(Arr data){
       /*
        * //系统通知
        SYSTEM,
        //工作流
        WORKFLOW,
        //台账信息
        ACC_LOAN,
        //短消息
        MESSAGE,
        //企查查通知
        QCC
        * */
        data.forEach( k->{
            Map mp = (Map)k;
//            System.err.println(k);
            switch(mp.get("type").toString()){
                case "SYSTEM":
                    mp.put("type","系统通知");
                    break;
                case "WORKFLOW":
                    mp.put("type","工作流");
                    break;
                case "ACC_LOAN":
                    mp.put("type","台账信息");
                    break;
                case "MESSAGE":
                    mp.put("type","短消息");
                    break;
                case "QCC":
                    mp.put("type","企查查通知");
                    break;
                case "BPM-MESSAGE":
                    mp.put("type","流程消息");
                    break;
            }
            if(mp.get("state") != null){
                if(mp.get("state").toString().equals("READ")){
                    mp.put("state","已读");
                }else if(mp.get("state").toString().equals("UNREAD")){
                    mp.put("state","未读");
                }
            }
//            System.err.println(mp.get("from_uid"));
            if(mp.get("from_uid") != null) {
                Arr user = db.getCollection("user").find(o(
                        "id", mp.get("from_uid")
                ).toBson()).into(a());
//                System.err.println(((Map) user.get(0)));
                mp.put("true_name", ((Map) user.get(0)).get("true_name"));
            }
            if(mp.get("true_name") == null){
                mp.put("true_name","系统");
            }
        });
        return data;
    }
}
